<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas width="600" height="400"></canvas>

    <script>
        var myCanvas = document.querySelector('canvas');
        var ctx = myCanvas.getContext('2d');

        var w = ctx.canvas.width;
        var h = ctx.canvas.height;

        //原点坐标
        var x0 = w / 2;
        var y0 = h / 2;

        //数据
        var data = [12,10,35,27,8];
        //计算人数总和，再算出一个人相当于多少弧度
        var total = 0;
        data.forEach(function (item) {
            total += item;
        });
        //一个人多少弧度(一个圆是 2π 弧度)
        var angle = 2 * Math.PI / total;
        
        function getColor () {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            // return "rgb(,"+r+","+g+","+b+")";
            return "rgb("+r+","+g+","+b+")";
        }

        var startAngle = 0;
        var endAngle = 0;
        // var num = 0;
        for (let i=0; i< data.length; i++) {
            // num += data[i];
            // endAngle = num * angle;
            endAngle = data[i] * angle + startAngle;
            ctx.beginPath();
            ctx.moveTo(x0, y0);
            ctx.arc(x0, y0, 150, startAngle, endAngle);
            // ctx.closePath();
            ctx.fillStyle = getColor();
            ctx.fill();

            //记录本次结束的弧度，就是下次的开始弧度
            startAngle = endAngle;
        }

        


    </script>
    
</body>
</html>